<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="商品名称">
                <a-input v-model="queryParam.name" placeholder="请输入商品名称" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="商品分类">
                <a-cascader
                  :options="catList"
                  @change="onCascaderChange"
                  :fieldNames="{ label: 'name', value: 'id', children: 'children' }"
                  placeholder="请选择商品分类"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="价格类型">
                <a-select v-model="queryParam.price_type" allowClear>
                  <a-select-option :key="1"> 成本价 </a-select-option>
                  <a-select-option :key="2"> 销售价 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="价格区间">
                <div class="numberBox" style="display: flex; align-items: center">
                  <div class="inp" style="flex: 1">
                    <a-input-number
                      :precision="2"
                      style="width: 100%"
                      v-model="queryParam.low_price"
                      :min="0"
                    ></a-input-number>
                  </div>
                  <span style="padding: 0 5px">~</span>
                  <div class="inp" style="flex: 1">
                    <a-input-number
                      v-model="queryParam.high_price"
                      :precision="2"
                      style="width: 100%"
                      :min="queryParam.low_price + 0.01"
                    ></a-input-number>
                  </div>
                </div>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="库存区间">
                <div class="numberBox" style="display: flex; align-items: center">
                  <div class="inp" style="flex: 1">
                    <a-input-number style="width: 100%" v-model="queryParam.low_num" :min="0"></a-input-number>
                  </div>
                  <span style="padding: 0 5px">~</span>
                  <div class="inp" style="flex: 1">
                    <a-input-number
                      v-model="queryParam.high_num"
                      style="width: 100%"
                      :min="queryParam.low_num + 1"
                    ></a-input-number>
                  </div>
                </div>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="比例筛选">
                <a-select v-model="queryParam.is_league">
                  <a-select-option key="-1">全部</a-select-option>
                  <a-select-option key="0">未设置</a-select-option>
                  <a-select-option key="1">已设置</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="供货商">
                <div class="flex">
                  <a-select v-model="queryParam.supplier_id" allowClear>
                    <a-select-option :key="0">全部</a-select-option>
                    <a-select-option :key="item.id" v-for="item in supplier_list">
                      {{ item.supplier_name }}</a-select-option
                    >
                  </a-select>

                  <a-button type="primary" @click="getList()"> 查询 </a-button>
                </div>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>

    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="getList()">
          <a-radio-button :value="item.id" :key="item.id" v-for="item of statusList">
            {{ item.title }}
          </a-radio-button>
        </a-radio-group>
      </div>

      <a-table
        style="width: 100%; overflow-x: auto"
        size="default"
        :columns="columns"
        :data-source="list"
        :row-key="(record) => record.id"
        :pagination="{
          current: pageNo,
          total: total,
          pageSize: pageSize,
          showSizeChanger: false,
          onChange: tablePageChange,
        }"
      >
        <span slot="goodInfo" slot-scope="text, record">
          <div class="content">
            <div class="img">
              <a-avatar shape="square" :size="48" icon="user" :src="record.cover_pic" />
            </div>

            <div class="txt">
              <a-tooltip>
                <template slot="title"> {{ record.name }} </template>
                <h3>{{ record.name }}</h3>
              </a-tooltip>
            </div>
          </div>
        </span>

        <span slot="price" slot-scope="text"> ¥{{ text || 0 }} </span>
        <span slot="goods_send_profit" slot-scope="text"> {{ text || 0 }}% </span>
        <span slot="goods_take_price" slot-scope="text"> {{ text || 0 }}% </span>

        <span slot="action" slot-scope="text, record">
          <a-button type="link" size="small" @click="handleItem('edit', record)">编辑</a-button>
        </span>
      </a-table>
    </a-card>

    <a-modal
      :title="form.id ? '修改' : '新增'"
      width="800px"
      v-model="visible"
      @ok="submit"
      :afterClose="closeModal"
      :destroyOnClose="true"
      :confirmLoading="btnLoading"
    >
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
        <a-form-model-item
          label="扣除联盟券比例"
          prop="goods_take_price"
          help="用户下单时扣除的联盟券比例，在下单时扣除，如有退货售后情况发生会立即退回"
        >
          <a-input v-model="form.goods_take_price" type="number" :step="0.01" suffix="%" />
        </a-form-model-item>
        <a-form-model-item label="赠送联盟券比例" prop="goods_send_profit" help="赠送用户的联盟券比例，在售后期发放">
          <a-input v-model="form.goods_send_profit" type="number" :step="0.01" suffix="%" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { list as catListApi } from '@/api/goods/cat'
import { list } from '@/api/goods/goods'
import { supplierList } from '@/api/purchase/purchase'
import { saveLeague } from '@/api/goods/goods'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '商品信息',
    dataIndex: 'goodInfo',
    scopedSlots: {
      customRender: 'goodInfo',
    },
    ellipsis: true,
  },
  {
    title: '销售价格',
    dataIndex: 'price',
    scopedSlots: {
      customRender: 'price',
    },
    sorter: (a, b) => parseFloat(a.price) - parseFloat(b.price),
  },
  {
    title: '赠送比例',
    dataIndex: 'goods_send_profit',
    scopedSlots: {
      customRender: 'goods_send_profit',
    },
    sorter: (a, b) => parseFloat(a.goods_send_profit) - parseFloat(b.goods_send_profit),
  },
  {
    title: '扣除比例',
    dataIndex: 'goods_take_price',
    scopedSlots: {
      customRender: 'goods_take_price',
    },
    sorter: (a, b) => parseFloat(a.goods_take_price) - parseFloat(b.goods_take_price),
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
    width: 150,
  },
]

export default {
  data() {
    return {
      total: 0,
      pageNo: 1,
      pageSize: 10,
      columns,

      list: [],
      selectedRowKeys: [],
      statusList: [
        { id: '-1', title: '全部' },
        { id: '1', title: '上架中' },
        { id: '0', title: '已下架' },
      ],

      catList: [],
      queryParam: {
        name: '',
        cat_id: 0,
        status: '-1',
        mch_id: 0,
        product_type: '0',
        price_type: 2,
        low_price: '',
        high_price: '',
        low_num: '',
        high_num: '',
        supplier_id: 0,
        is_league: '-1',
      },

      visible: false,
      btnLoading: false,
      form: {
        goods_send_profit: '',
        goods_take_price: '',
      },

      rules: {
        goods_send_profit: [{ required: true, message: '请输入', trigger: 'blur' }],
        goods_take_price: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
    }
  },

  mounted() {
    this.getList()
    this.supplierList()
    this.getCatList()
  },

  computed: {
    getStatus() {
      return (status) => {
        let text, color
        switch (String(status)) {
          case '0':
            text = '未审核'
            color = 'rgba(0, 0, 0, 0.25)'
            break

          case '1':
            text = '已通过'
            color = '#65C817'
            break

          case '2':
            text = '已拒绝'
            color = '#FF4D4F'
            break
        }
        return [text, color]
      }
    },
  },

  methods: {
    async supplierList() {
      const res = await supplierList({ limit: 50, page: 1 })
      if (res.code === 0) {
        this.supplier_list = res.data.list
      }
    },

    getCatList() {
      catListApi({ is_show: -1 }).then((res) => {
        this.catList = res.data.list
      })
    },

    onCascaderChange(val) {
      this.queryParam.cat_id = val[val.length - 1]
    },

    // 获取数据列表
    async getList(pageNo = 1) {
      const hide = this.$message.loading('加载中', 0)
      let { queryParam, pageSize } = this

      const res = await list({
        ...queryParam,
        pageSize,
        pageNo,
      })

      if (res.code == 0) {
        this.pageNo = pageNo
        this.selectedRowKeys = []
        let { totalCount, data } = res.data
        this.total = totalCount
        this.list = data
      }

      hide()
    },

    // 分页请求
    tablePageChange(e) {
      this.getList(e)
    },

    // 点击单个
    handleItem(type, item) {
      switch (type) {
        case 'edit':
          this.form = {
            id: item.id,
            goods_send_profit: item.goods_send_profit,
            goods_take_price: item.goods_take_price,
          }
          this.visible = true
          break
      }
    },

    submit() {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form))

          this.btnLoading = true
          let res = await saveLeague(form)
          if (res.code == 0) {
            this.$message.success('操作成功')
            this.visible = false
            this.getList(this.pageNo)
          } else {
            this.$message.error(res.msg)
          }
          this.btnLoading = false
        } else {
          return false
        }
      })
    },

    closeModal() {
      this.$refs['ruleForm'].resetFields()
    },
  },
}
</script>

<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 8px 0 18px 0;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-right: 20px;
  }
}

.content {
  display: flex;
  align-items: center;
  margin-right: 10px;
  height: 48px;
  max-width: 500px;
  overflow: hidden;

  .txt {
    margin-left: 16px;
    flex: 1;
    overflow: hidden;

    * {
      margin: 0;
      font-size: 14px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }

    h3 {
      color: rgba(0, 0, 0, 0.85);
    }

    p {
      color: rgba(0, 0, 0, 0.45);
    }
  }
}

.flex {
  .inp {
    margin-right: 16px;
  }
}
</style>
